<template>
	<view class="content" v-if="grabList">
		<uv-navbar :title="title" @leftClick="leftClick" placeholder></uv-navbar>
		<view class="" v-if="grabList.length>0">
			<view class="m-t-20" v-for="(item,index) in grabList" :key="index">
				<view class="center_list" v-if="item.countdown">
					<view class="text-c bold m-t-20">
						剩余：<text style="color: red;">{{item.countdown}}</text> 秒
					</view>
					<view class="flex m-t-50" v-if="pageFrom.platform==2" @click="orderInfo(item)">
						<image class="w-150 h-150" :src="item.productImg" mode=""></image>
						<view class="m-l-20 flex flex-column3" style="flex: 1;">
							<view class="bold">{{item.productName}}</view>
							<view class="">
								<view class="size-28 w-80 text-c radius-10 m-t-10" style="border: 5rpx solid #e3e3e3;color: #e39b30;">
									外带
								</view>
							</view>
							<view class="size-30 m-t-10 bold" style="color: #999;">
								{{item.storeName}}
							</view>
							<view class="size-28 m-t-10 flex-b" style="color: #999;">
								<text>市场价：￥{{item.totalAmount}}</text>
								<view class="flex">
									<uv-icon name="map"></uv-icon>
									<text>{{item.newOrderContent.cityName}}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="flex m-t-50" v-if="pageFrom.platform==3" @click="orderInfo(item)">
						<image class="w-150 h-150" :src="item.productImg" mode=""></image>
						<view class="m-l-20 flex flex-column3" style="flex: 1;">
							<view class="bold">{{item.productName}}</view>
							<view class="">
								<view class="size-28 w-80 text-c radius-10 m-t-10" style="border: 5rpx solid #e3e3e3;color: #e39b30;">
									自提
								</view>
							</view>
							<view class="size-30 m-t-10 bold" style="color: #999;">
								{{item.storeName}}
							</view>
							<view class="size-28 m-t-10 flex-b" style="color: #999;">
								<text>市场价：￥{{item.totalAmount}}</text>
								<view class="flex">
									<uv-icon name="map"></uv-icon>
									<text>{{item.newOrderContent.cityName}}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="flex m-t-50" v-if="pageFrom.platform==4" @click="orderInfo(item)">
						<image class="w-150 h-150" :src="item.productImg" mode=""></image>
						<view class="m-l-20 flex flex-column3" style="flex: 1;">
							<view class="bold">{{item.productName}}</view>
							<view class="">
								<view class="size-28 w-80 text-c radius-10 m-t-10" style="border: 5rpx solid #e3e3e3;color: #e39b30;">
									外带
								</view>
							</view>
							<view class="size-30 m-t-10 bold" style="color: #999;">
								{{item.storeName}}
							</view>
							<view class="size-28 m-t-10 flex-b" style="color: #999;">
								<text>市场价：￥{{item.totalAmount}}</text>
								<view class="flex">
									<uv-icon name="map"></uv-icon>
									<text>{{item.newOrderContent.cityName}}</text>
								</view>
							</view>
						</view>
					</view>
					<view class="flex m-t-50" v-if="pageFrom.platform==6" @click="orderInfo(item)">
						<image class="w-150 h-150" :src="item.productImg" mode=""></image>
						<view class="m-l-20 flex flex-column3" style="flex: 1;">
							<view class="bold">{{item.productName}}</view>
							<view class="">
								<view class="size-28 w-80 text-c radius-10 m-t-10" style="border: 5rpx solid #e3e3e3;color: #e39b30;">
									外带
								</view>
							</view>
							<view class="size-30 m-t-10 bold" style="color: #999;">
								{{item.storeName}}
							</view>
							<view class="size-28 m-t-10 flex-b" style="color: #999;">
								<text>市场价：￥{{item.totalAmount}}</text>
								<view class="flex">
									<uv-icon name="map"></uv-icon>
									<text>{{item.newOrderContent.cityName}}</text>
								</view>
							</view>
						</view>
					</view>
					<view @click="grabOk(item)" class="p-y-15 text-c radius-10 white bold m-t-20" style="background-color: #e33d30;">
						抢单
					</view>
					<view class="po-a p-y-15 p-x-10" style="top: 0%;right: 2%;background-color: #e33d30;border-radius: 0 0 10rpx 10rpx;">
						<text class="bold white">
						  {{item.realTotalAmount}}
						  <text class="size-28">元</text>
						 </text>
					</view>
					<view class="po-a" style="left: -1%;top: -2%;">
						<image class="w-100 h-100" src="/static/image/label.png" mode=""></image>
						<view class="po-a white size-24 bold" style="top: 20%;left: 30%;">
							新
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="po-a po-atl" v-else>
			<view class="text-c">
				<image class="w-200 h-200" src="../../static/image/noProduct.png" mode=""></image>
				<view class="size-32 color-gray">
					抢单内容为空~
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		toRefs,
		onMounted,
		onUnmounted
	} from "vue";
	import {
		onLoad,
		onReachBottom,
		onShow,
		onLaunch,
		onReady,
		onUnload,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import {grabLists,grabTo} from '@/api/index.js'
	import {dataGong,sortJsonKeys,sortAndFormatParams,combine} from '@/utils/encryption.js'
	let pageFrom = {
		pageNum: 1,
		pageSize: 10,
		platform:undefined
	}
	const data = reactive({
		title:'',
		grabList:[],
		total:0,
	})
	// 初始化倒计时
	let timerId = setInterval(updateCountdown, 1000);
	const {
		title,
		grabList,
		total,
	} = toRefs(data)
	onUnmounted(() => clearInterval(timerId));
	onShow(()=>{
		pageFrom.pageNum = 1
		grabList.value = []
		getGrabLists()
	})
	onLoad((value)=>{
		// const pages = getCurrentPages();  
		// const page = pages[pages.length - 1];
		// const eventChannel = page.getOpenerEventChannel();
		// eventChannel.on('grabOkEvent', (data) => {
		// 	console.log(data);
		// 	grabOk(data);
		// });
		if(value.platform){
			uni.setStorageSync('platform',value.platform)
			switch (value.platform){
				case '1':
					title.value = '麦当劳'
					uni.setStorageSync('platName',title.value)
				break;
				case '2':
					title.value = '肯德基'
					uni.setStorageSync('platName',title.value)
				break;
				case '3':
					title.value = '瑞幸咖啡'
					uni.setStorageSync('platName',title.value)
				break;
				case '4':
					title.value = '汉堡王'
					uni.setStorageSync('platName',title.value)
				break;
				case '6':
					title.value = '德克士'
					uni.setStorageSync('platName',title.value)
				break;
				default:
					title.value = ''
				break;
			}
		}
		pageFrom.platform = uni.getStorageSync('platform')
		title.value = uni.getStorageSync('platName')
		// getGrabLists()
	})
	const getGrabLists = ()=>{
		let cityJinWei = {
			...dataGong(),
			...pageFrom
		}
		let cenShi = sortAndFormatParams(cityJinWei) //请求序列化并变成字符串
		let combineTrue = combine(cenShi, cityJinWei.timestamp)
		
		grabLists(cityJinWei,combineTrue).then(res=>{
			res.data.forEach(item=>{
				item.orderContent = JSON.parse(item.orderContent)
			})
			total.value = res.total
			grabList.value = [
				...grabList.value,
				...res.data
			]
			grabList.value.forEach(item=>{
				  let createTime = new Date(item.createTime).getTime(); // 创建时间
				  console.log(createTime);
				  const countdownSeconds = item.receivingTimeNum;     // 剩余秒数
				  const endTime = createTime + countdownSeconds * 1000
				  console.log('endTime-------',endTime);
				  item.endTime = endTime
			})
		})
		console.log('grabList',grabList);
	}
	
	function updateCountdown (){
		grabList.value = grabList.value.map(order => {
			const now = Date.now();
			if (now >= order.endTime) {
				order.countdown = '已超时'; // 如果当前时间超过结束时间，则标记为超时
				order.isExpired = true
			} else {
				const diff = Math.max(0, parseInt((order.endTime - now) / 1000)); // 计算剩余秒数
				order.countdown = formatSeconds(diff);
			}
			return order
		}).filter(order => !order.isExpired)
	}
	
	const formatSeconds = (seconds) => {
		const h = Math.floor(seconds / 3600);
		const m = Math.floor((seconds % 3600) / 60);
		const s = seconds % 60;
		return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
	}
	
	// 下拉刷新
	onPullDownRefresh(async()=>{
		pageFrom.pageNum=1
		grabList.value = []
	   await getGrabLists()
		setTimeout(()=>{
			uni.stopPullDownRefresh() 
		},500)
	})
	// 上拉加载
	onReachBottom(()=>{
		if(grabList.value.length==total.value){
			uni.showToast({
				title: '暂无更多内容',
				icon: "none",
			})
			return
		}
		pageFrom.pageNum+=1
		getGrabLists()
	})
	// 查看商品详情
	const orderInfo = (value)=>{
		console.log(value);
		uni.navigateTo({
			url:`/pagesA/grab/grabQuotation?id=${value.id}&merchantId=${value.merchantId}&type=1&status=0`
		})
	}
	// 抢单
	const grabOk = (value)=>{
		// console.log(value);
		let cityJinWei = {
			id:value.id,
			merchantId:value.merchantId,
			...dataGong()
		}
		let cenShi = sortAndFormatParams(cityJinWei) //请求序列化并变成字符串
		let combineTrue = combine(cenShi, cityJinWei.timestamp)
		grabTo(cityJinWei,combineTrue).then(res=>{
			if(res.code==0){
				uni.showToast({
					title: res.message,
					icon: "none",
				})
				grabList.value.forEach((item,index)=>{
					grabList.value = grabList.value.filter(item=>item.id!=value.id)
				})
				uni.navigateTo({
					url:`/pagesA/grab/grabQuotation?id=${value.id}&merchantId=${value.merchantId}&type=2&status=2`
				})
			} else {
				uni.showToast({
					title: res.message,
					icon: "none",
				})
			}
		})
		
	}
	
	const leftClick = ()=>{
		uni.switchTab({
			url:'/pages/home/home'
		})
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #f9f9f9;
	}
	.content {
		padding: 10rpx 20rpx 20rpx 20rpx;
		.center_list{
			padding: 10rpx 20rpx 20rpx 20rpx;
			background-color: #fff;
			// margin-top: 20rpx;
			border-radius: 10rpx;
			position: relative;
		}
		.center_list:first-child{
			margin-top: 0rpx;
		}
	}
</style>
